﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

namespace UI.Tools
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler
    {
        string area = string.Empty;
        int count = 0;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            area = HttpContext.Current.Request["area"];
            string path = UploadFile();
            string result = PostImg(path);
            context.Response.Write(result);
            context.Response.End();
        }
        public string PostImg(string Path)
        {
            WeiXin wx = new WeiXin();
            string url = wx.FindUrl(area, "Upload");
            using (FileStream fileStream = new FileStream(Path, FileMode.Open, FileAccess.Read))
            {
                IDictionary<string, string> postParameter = new Dictionary<string, string>();
                postParameter.Add("handle", HttpContext.Current.Request["handle"]);
                string result = HttpUploadClient.Execute(new UploadParameterType
                {
                    Url = url,
                    UploadStream = fileStream,
                    FileNameValue = "filename.png",
                    PostParameters = postParameter
                });
                return result;
            }

        }
        public string UploadFile()
        {
            count++;
            int random = new Random(DateTime.Now.Millisecond).Next(1, 100) + count;
            string opath = "/upload/"+ area + "/";
            var rootpath = HttpContext.Current.Server.MapPath(opath);
            if (!System.IO.Directory.Exists(rootpath))
            {
                Directory.CreateDirectory(rootpath);
            }
            dynamic obj = new ExpandoObject();
            string path = string.Empty;
            for (int j = 0; j < HttpContext.Current.Request.Files.Count; j++)
            {
                HttpPostedFile uploadFile = HttpContext.Current.Request.Files[j];
                if (uploadFile.ContentLength > 0)
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = random.ToString();
                    string file = rootpath + unique + ext;
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    path = file;
                }
            }
            return path;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}